package com.suda.sudaexamsystem.controller;

import com.suda.sudaexamsystem.dto.ClazzDto;
import com.suda.sudaexamsystem.pojo.Clazz;
import com.suda.sudaexamsystem.pojo.User;
import com.suda.sudaexamsystem.service.ClazzService;
import com.suda.sudaexamsystem.service.UserService;
import com.suda.sudaexamsystem.util.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private ClazzService clazzService;

    /*
    注册 name loginName password sex
    请求地址：localhost:8080/user/register  类使用了@RequestMapping("/user")
     */
    @PostMapping(value = "/register", produces = {"application/json;charset=UTF-8"})
    public AjaxResult registerUser(User user) {
        userService.registerUser(user);
        return AjaxResult.success();
    }

    /*
    登录
    {"msg":"操作成功","code":200,"data":{"id":1,"name":"admin","login_name":"段智兴","sex":"男"}}
     */
    @PostMapping(value = "/login", produces = {"application/json;charset=UTF-8"})
    public AjaxResult login(String name, String password) {
        User user = userService.findByNameAndPassword(name, password);
        log.info("name：" + name + ", password：" + password);
        if (user == null) {
            return AjaxResult.error("用户不存在或密码输入错误");
        }
        return AjaxResult.success(user.toDto());
    }

    @GetMapping(value = "/test", produces = {"application/json;charset=UTF-8"})
    public AjaxResult test() {
        User user = userService.findByNameAndPassword("admin", "123456");
        return AjaxResult.success(user.toDto());
    }

    /*
    查询用户的班级
    {"msg":"操作成功","code":200,"data":[{"id":1,"name":"神雕侠侣","owner":{"id":1,"name":"admin","login_name":"段智兴","sex":"男"}},
    {"id":2,"name":"大理","owner":{"id":1,"name":"admin","login_name":"段智兴","sex":"男"}}]}
     */
    @GetMapping(value = "/clazz/{userId}", produces = {"application/json;charset=UTF-8"})
    public AjaxResult findClazz(@PathVariable("userId") int userId) {
        List<Clazz> clazzList = clazzService.findByUserId(userId);
        List<ClazzDto> clazzDtoList = new ArrayList<>();
        for (Clazz clazz : clazzList) {
            ClazzDto clazzDto = clazz.toDto();
            clazzDto.setOwner(clazz.getOwner().toDto());
            clazzDtoList.add(clazzDto);
        }
        return AjaxResult.success(clazzDtoList);
    }
}
